package com.dream.network.utils;

import android.util.Log;

import com.dream.network.GlobalInit;
import com.dream.network.HttpRequest;
import com.dream.network.HttpResponse;
import com.dream.network.HttpTask;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Description: TODO
 * author: Wang
 * date: 3/9/17 16:52
 * email:life_artist@163.com
 * Copyright©2017 by wang. All rights reserved.
 */
public class HttpClient {

    public static final int CONNECTION_TIME_OUT = 5 * 1000;
    public static final int READ_DATA_TIME_OUT = 5 * 1000;
    public static final int WRITE_DATA_TIME_OUT = 5 * 1000;
    private static String sUserAgent;
    private static HttpClient sInstance;
    private OkHttpClient mClient;

    public HttpClient() {
        mClient = newClient();
    }

    public static HttpClient getInstance() {
        if (sInstance == null) {
            synchronized (HttpClient.class) {
                if (sInstance == null) {
                    sInstance = new HttpClient();
                }
            }
        }
        return sInstance;
    }

    public static HttpTask addRequest(HttpRequest request) {
        if (request == null) {
            return null;
        }
        Request requestInfo = getRequest(request);
        Call call = getInstance().getClient().newCall(requestInfo);
        HttpTask task = new HttpTask();
        task.setRequest(request);
        task.enqueue(call);
        return task;
    }

    public static HttpResponse addRequestSync(HttpRequest request) {
        if (request == null) {
            return null;
        }

        Call call = getInstance().getClient().newCall(getRequest(request));
        try {
            return new HttpResponse(call.execute());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public OkHttpClient getClient() {
        return mClient;
    }

    /**
     * 创建默认的OkHttpClient
     */
    private static OkHttpClient newClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(CONNECTION_TIME_OUT, TimeUnit.MILLISECONDS);
        builder.readTimeout(READ_DATA_TIME_OUT, TimeUnit.MILLISECONDS);
        builder.writeTimeout(WRITE_DATA_TIME_OUT, TimeUnit.MILLISECONDS);
        builder.retryOnConnectionFailure(true);
        //builder.sslSocketFactory(getSSLSocketFactory());
        return builder.build();
    }

    private static Request getRequest(HttpRequest request) {
        if (request == null)
            return null;

        Request.Builder builder = new Request.Builder();
        String url = request.getUrl();
        if (HttpRequest.HttpMethod.GET == request.mMethod) {
            url += request.getParameterForGet();
        }

        if (GlobalInit.APP_DEBUG) {
            Log.d(GlobalInit.HTTP_TAG, "Http Url：" + url);
        }

        builder.url(url);
        builder.tag(request.getTag());
        builder.headers(request.getRequestHeaders());
        switch (request.mMethod) {
            case HttpRequest.HttpMethod.GET:
                builder.get();
                break;
            case HttpRequest.HttpMethod.POST:
                if (request.isFilePost() || request.isStreamPost()) {
                    builder.post(request.getRequestBodyFile());
                } else if (request.isBytePost()) {
                    builder.post(request.getRequestBodyInputStream());
                } else if (request.isJsonStrPost()) {
                    builder.post(request.getJsonRequestBody());
                } else {
                    builder.post(request.getRequestBody());
                }
                break;
            default:
                throw new RuntimeException("Unsupported http method.");
        }
        return builder.build();
    }

    /**
     * 加载证书
     */
//    private static X509Certificate loadCertificate(int id) {
//        InputStream in = null;
//        try {
//            CertificateFactory cf = CertificateFactory.getInstance("X.509");
//            in = BaseApplication.getContext().getResources().openRawResource(id);
//            X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
//            return cert;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        } finally {
//            if (in != null) {
//                try {
//                    in.close();
//                } catch (IOException e) {
//                }
//            }
//        }
//    }
}
